﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;

namespace com.yd.sdk.api
{
    public class PayManager : MonoBehaviour,IPay,IPayListener
    {
        [Header("Google Billings")]
        public string ConsumeSku, NonConsumeSku, SubsSku;
        public event UnityAction HandleIAPServerDisconnected;
        public event UnityAction HandleIAPSetUpSuccess;
        public event UnityAction<string> HandleIAPSetUpFailed;
        public event UnityAction<string> HandleIAPPurchaseSuccess;
        public event UnityAction<string, string> HandleIAPPurchaseFailed;
        public event UnityAction<string> HandleQueryPurchaseHistorySucess;
        public event UnityAction<string> HandleQueryPurchaseHistoryFailed;

        public static PayManager Ins;
        
        void Awake()
        {
            Ins = this;
        }

        // Start is called before the first frame update
        void Start()
        {
            //Initialized(ConsumeSku, NonConsumeSku, SubsSku);
            DontDestroyOnLoad(gameObject);
        }

        // Update is called once per frame
        void Update()
        {
        
        }

        // #region Test
        //
        // public void Init()
        // {
        //     
        // }
        //
        // public void Purchase(string str)
        // {
        //     PurchaseProduct(str);
        // }
        //
        //
        // #endregion
        
        
        #region 外部使用
        
        public void Initialized(string ConsumeSku, string NonConsumeSku, string SubsSku)
        {
            #if UNITY_EDITOR
                Debug.Log("Initialized=>Editor not support");        
            #elif UNITY_ANDROID
                Debug.Log("调用Initialized");
                JavaPayManager?.Call("Initialized", ConsumeSku??"", NonConsumeSku??"", SubsSku??"");          
            #elif UNITY_IPHONE || UNITY_IOS
                                
            #else
                            
            #endif
            
        }

        /// <summary>
        /// 初始化
        /// key:skuName
        /// value 0消费品,1非消费,2订阅
        /// </summary>
        /// <param name="type">dic</param>
        public void Initialized(Dictionary<string,int> type)
        {
            List<string> consumeSkuList = new List<string>();
            List<string> nonConsumeSkuList = new List<string>();
            List<string> subsSkuList = new List<string>();
            
            foreach (var keyValuePair in type)
            {
                if (keyValuePair.Value == 0)
                    consumeSkuList.Add(keyValuePair.Key);
                else if (keyValuePair.Value == 1)
                    nonConsumeSkuList.Add(keyValuePair.Key);
                else if(keyValuePair.Value == 2)
                    subsSkuList.Add(keyValuePair.Key);
            }

            JavaPayManager?.Call("Initialized",
                consumeSkuList.Count > 0 ? string.Join(",", consumeSkuList) : "",
                nonConsumeSkuList.Count > 0 ? string.Join(",", nonConsumeSkuList) : "",
                subsSkuList.Count > 0 ? string.Join(",", subsSkuList) : "");
        }
        
        public void PurchaseProduct(string productInfo)
        {
            #if UNITY_EDITOR
                Debug.Log("Initialized=>Editor not support");        
            #elif UNITY_ANDROID
                Debug.Log("调用PurchaseProduct");
                JavaPayManager?.Call("PurchaseProduct", productInfo);                  
            #elif UNITY_IPHONE || UNITY_IOS
                                            
            #else
                                        
            #endif
            
        }

        public int GetConnectionState()
        {
            #if UNITY_EDITOR
                 Debug.Log("Initialized=>Editor not support");        
            #elif UNITY_ANDROID
                 return JavaPayManager?.Call<int>("GetConnectionState") ?? 0;                              
            #elif UNITY_IPHONE || UNITY_IOS
                                                        
            #else
                                                    
            #endif

            return 0;
        }

        public void QueryPurchaseHistory()
        {
            #if UNITY_EDITOR
                Debug.Log("Initialized=>Editor not support");        
            #elif UNITY_ANDROID
                JavaPayManager?.Call("QueryPurchaseHistory");                                   
            #elif UNITY_IPHONE || UNITY_IOS
                                                        
            #else
                                                    
            #endif
        }

        public bool IsReady()
        {
            // return JavaPayManager?.Call<bool>("IsReady") ?? false;
            return GetConnectionState() == 2;
        }

        #endregion
        
        #region Java回调Wrapper

        //调用payManager的类
        private AndroidJavaObject _javaPayManager;
        private AndroidJavaObject JavaPayManager {
            get
            {
                #if UNITY_EDITOR
                    Debug.Log("JavaPayManager=>Editor not support");        
                #elif UNITY_ANDROID
                    _javaPayManager = _javaPayManager ?? JavaActivity.GetStatic<AndroidJavaObject>("payManager");
                #elif UNITY_IPHONE || UNITY_IOS
                                                                        
                #else
                                                                        
                #endif
                
                return _javaPayManager;
            }
        }

        private AndroidJavaClass _javaActivity;
        private AndroidJavaClass JavaActivity
        {
            get
            {
                _javaActivity = _javaActivity ?? new AndroidJavaClass(Const.MyUnityPlayerActivity);
                return _javaActivity;
            }
        }
        
        
        #endregion

        

        public void OnIAPServerDisconnected()
        {
            Debug.Log("OnIAPServerDisconnected");
            HandleIAPServerDisconnected?.Invoke();
        }

        public void OnIAPSetUpSuccess()
        {
            Debug.Log("OnIAPSetUpSuccess");
            HandleIAPSetUpSuccess?.Invoke();
        }

        public void OnIAPSetUpFailed(string message)
        {
            Debug.Log("OnIAPSetUpFailed:" + message);
            HandleIAPSetUpFailed?.Invoke(message);
        }

        public void OnIAPPurchaseSuccess(string message)
        {
            Debug.Log("OnIAPPurchaseSuccess:" + message);
            HandleIAPPurchaseSuccess?.Invoke(message);
        }

        public void OnIAPPurchaseFailed(string name, string message)
        {
            Debug.Log("OnIAPPurchaseFailed:"+name+","+message);
            HandleIAPPurchaseFailed?.Invoke(name, message);
        }

        public void OnQueryPurchaseHistorySucess(string skus)
        {
            HandleQueryPurchaseHistorySucess?.Invoke(skus);
        }

        public void OnQueryPurchaseHistoryFailed(string message)
        {
            HandleQueryPurchaseHistoryFailed?.Invoke(message);
        }
        
        public void OnIAPPurchaseFailed(string message)
        {
            var stringArray = message.Split(':');
            if (stringArray.Length >= 2)
            {
                OnIAPPurchaseFailed(stringArray[0],stringArray[1]);
            }
        }

    }
}
